package com.chhuang.ewcrm.string;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;

/**
 *
 * @ClassName: Base64CodeUtil
 * @Description: base64加密与解密
 * @author: 黄晨
 * @date: 2015-7-9
 *
 */
public class Base64CodeUtil {
	private Base64CodeUtil(){}

	/**
	 * 字符串base64编码为字符串
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		String result = null;

		if(StringUtils.isNotEmpty(str)) {
			result = Base64.encodeBase64String(str.getBytes());
		}

		return result;
	}

	/**
	 * 字节数组base64编码为字符串
	 * @param bytes
	 * @return
	 */
	public static String encode(byte[] bytes) {
		String result = null;

		if(bytes!=null && bytes.length>0) {
			result = Base64.encodeBase64String(bytes);
		}

		return result;
	}

	/**
	 * 字符串base64解码为字符串
	 * @param str
	 * @return
	 */
	public static String decode(String str) {
		String result = null;

		if(StringUtils.isNotEmpty(str)) {
			result = new String(Base64.decodeBase64(str.getBytes()));
		}

		return result;
	}

	/**
	 * 字节数组base64解码为字符串
	 * @param bytes
	 * @return
	 */
	public static String decode(byte[] bytes) {
		String result = null;

		if(bytes!=null && bytes.length>0) {
			result = new String(Base64.decodeBase64(bytes));
		}

		return result;
	}

	/**
	 * 字符串base64编码为字符串
	 * @param str
	 * @return
	 */
	public static byte[] encode2bytes(String str) {
		byte[] result = null;

		if(StringUtils.isNotEmpty(str)) {
			result = Base64.encodeBase64(str.getBytes());
		}

		return result;
	}

	/**
	 * 字节数组base64编码为字符串
	 * @param bytes
	 * @return
	 */
	public static byte[] encode2bytes(byte[] bytes) {
		byte[] result = null;

		if(bytes!=null && bytes.length>0) {
			result = Base64.encodeBase64(bytes);
		}

		return result;
	}

	/**
	 * 字符串base64解码为字符串
	 * @param str
	 * @return
	 */
	public static byte[] decode2bytes(String str) {
		byte[] result = null;

		if(StringUtils.isNotEmpty(str)) {
			result = Base64.decodeBase64(str.getBytes());
		}

		return result;
	}

	/**
	 * 字节数组base64解码为字符串
	 * @param bytes
	 * @return
	 */
	public static byte[] decode2bytes(byte[] bytes) {
		byte[] result = null;

		if(bytes!=null && bytes.length>0) {
			result = Base64.decodeBase64(bytes);
		}

		return result;
	}

}
